//
//  CalendarDay+Create.m
//  planner
//
//  Created by 함동균 on 2014. 3. 21..
//  Copyright (c) 2014년 idea. All rights reserved.
//

#import "CalendarDay+Create.h"

@implementation CalendarDay (Create)

+ (CalendarDay *)setDate:(NSDate *) date inManagedObjectContext:(NSManagedObjectContext *)context
{
    CalendarDay *myCalendarDay = nil;
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"CalendarDay"];
    NSMutableArray *predicateArray = [NSMutableArray array];
    [predicateArray addObject:[NSPredicate predicateWithFormat:@"date = %@", date]];
    request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray];
    
    NSError *error;
    NSArray *matches = [context executeFetchRequest:request error:&error];
    
    if (!matches || error || [matches count] > 1) {
        // Handle error
    } else if ([matches count]) {
        return matches.firstObject;
    } else {
        myCalendarDay = [NSEntityDescription insertNewObjectForEntityForName:@"CalendarDay" inManagedObjectContext:context];
        myCalendarDay.date = [date timeIntervalSince1970];
        //[NSDate timeIntervalSinceDate:date];
        //[date timeIntervalSince1970];
    }
    
    return myCalendarDay;
}

- (NSString *)getDateString
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.date];
    NSDateComponents *component = [calendar components:unit fromDate:date];
    return [NSString stringWithFormat:@"%d", component.day];
}

- (NSInteger)getMonthInteger
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unit = NSCalendarUnitMonth;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.date];
    NSDateComponents *component = [calendar components:unit fromDate:date];
    return component.month;
}

- (Boolean)equalsToDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *datecomp1 = [calendar components:unit fromDate:[NSDate dateWithTimeIntervalSince1970:self.date]];
    NSDateComponents *datecomp2 = [calendar components:unit fromDate:date];
    
    if (datecomp1.year == datecomp2.year && datecomp1.month == datecomp2.month && datecomp1.day == datecomp2.day)
        return YES;
    else
        return NO;
}
@end
